# -*- coding:utf-8 -*-
import requests, pyquery, os, re, urllib3, asyncio, aiohttp

urllib3.disable_warnings()

tvList = []
downloadList = []
pattern = 'http://www.nvzox.com/v/889-1-%s.html'
tasks = []
sourceDir = None


# 得到电视剧的剧集列表
def buildList():
    global sourceDir
    sourceDir = os.getcwd()
    global tvList
    listUrl = 'http://www.nvzox.com/v/889-1-1.html'
    html = pyquery.PyQuery(url=listUrl)
    list = html.find('.sidecon li')

    for i in list:
        tvList.append(i.find('a').text[3:5])

    print('剧集列表:', tvList)


# 选择需要下载的剧集
def choseTv():
    global downloadList
    downloadList = [i.rjust(2, '0') for i in input('请选择需要下载的序号,多集请使用","分隔:').split(',')]
    print('下载列表', downloadList)


def getPath(i):
    global sourceDir
    path = os.path.join(sourceDir, i)
    return path


# 艹它~
def download():
    for i in downloadList:
        print('开始下载', i)
        # 创建存放ts文件的临时文件夹
        path = getPath(i)
        if not os.path.isdir(path):
            os.mkdir(path)
        os.chdir(path)

        # 得到伪装tsurl
        url = pattern % i
        dom = pyquery.PyQuery(url=url)
        jsonUlr = dom.find('#cms_player script').attr('src')
        print('获取页面信息', i)

        # 获取ts文件url
        jsonContent = requests.get('http://www.nvzox.com' + jsonUlr)
        jsonContent = jsonContent.content
        reg = re.compile(b'(https:\\\/\\\/youku.cdn4-okzy.com\\\/.*?\\\/.*?\\\/index.m3u8)')
        tsUrlList = str(reg.findall(jsonContent)[0], 'utf-8').split('/')
        tsUrlList.insert(-1, "1000k\/hls")
        url = '/'.join(tsUrlList).replace('\/', '/')
        downloadts(i, url)


def downloadts(tv, url):
    global tasks
    path = getPath(tv)
    os.chdir(path)

    # 获取m3u8文件的文本信息
    print('拉取视频列表', tv)
    all_content = requests.get(url=url, verify=False).text
    # 解析文本信息
    file_line = all_content.split("\n")
    if file_line[0] != "#EXTM3U":
        raise BaseException(u'非M3U8的链接')
    else:
        unknow = True
        for index, line in enumerate(file_line):
            try:
                if "#EXTINF" in line:
                    unknow = False
                    print('下载视频分段', tv, file_line[index + 1])
                    pd_url = url.replace('index.m3u8', '') + '/' + file_line[index + 1]
                    tasks.append(downloadtsslice(pd_url, file_line, index))
            except Exception as e:
                print(e)

    event_loop = asyncio.get_event_loop()
    results = event_loop.run_until_complete(asyncio.gather(*tasks))
    event_loop.close()


async def downloadtsslice(pd_url, file_line, index):
    async with aiohttp.request("GET", pd_url) as r:
        content = await r.read()
    c_fule_name = str(file_line[index + 1]).split('/')[-1]
    with open('./' + c_fule_name, 'ab') as f:
        f.write(content)
        f.flush()
